import WxValidate from "@/utils/WxValidate";

import type {
  WxValidateInstance,
  WxValidateMessagesInfo,
  WxValidateRulesInfo,
} from "@/utils/WxValidate.type";

Component<
  {
    formData: {
      switchChecked: boolean;
      radio: string;
      checkbox: string[];
      inputValue: string;
      inputValue2: string;
      [key: string]: any;
    };
    fieldsError: Record<string, string[]>;
  },
  {},
  {
    init: () => void;
    formSubmit: (e: WechatMiniprogram.CustomEvent) => void;
    formReset: (e: WechatMiniprogram.CustomEvent) => void;
    doFieldUpdateAndValidate: (field: string, fieldVal: any) => void;
    onSwitchChange: (e: WechatMiniprogram.CustomEvent) => void;
    onCheckboxChange: (e: WechatMiniprogram.CustomEvent) => void;
    onRadioChange: (e: WechatMiniprogram.CustomEvent) => void;
    onInputChange: (e: WechatMiniprogram.CustomEvent) => void;
  },
  {
    _wxValidate: WxValidateInstance;
  }
>({
  data: {
    formData: {
      switchChecked: false,
      radio: "1",
      checkbox: ["b"],
      inputValue: "",
      inputValue2: "",
    },
    /**
     * key为字段名
     * value为错误提示信息
     */
    fieldsError: {},
  },
  lifetimes: {
    ready() {
      this.init();
    },
  },
  methods: {
    init() {
      const rulesInfo: WxValidateRulesInfo = {
        checkbox: { required: true, arrLenGte: 2 },
        inputValue: { required: true },
        inputValue2: { required: true, sameInputValue: "inputValue" },
      };
      const messagesInfo: WxValidateMessagesInfo = {
        checkbox: {
          required: "复选组件必填",
        },
        inputValue: { required: "文本输入组件必填", arrLenGte: "至少选择2个" },
        inputValue2: {
          required: "文本输入组件必填",
          sameInputValue: "与文本输入组件输入的内容不一致",
        },
      };
      // 自定义验证规则
      this._wxValidate = new WxValidate(
        rulesInfo,
        messagesInfo
      ) as unknown as WxValidateInstance;
      this._wxValidate.addMethod(
        "arrLenGte",
        (value, param) => {
          return this._wxValidate.optional(value) || value.length >= param;
        },
        (config: number) => `至少勾选${config}个选项`
      );
      this._wxValidate.addMethod(
        "sameInputValue",
        (value, param) => {
          return (
            this._wxValidate.optional(value) ||
            value === this.data.formData[param]
          );
        },
        `与文本输入组件输入的内容不一致`
      );
      this.setData({
        formData: {
          switchChecked: false,
          radio: "1",
          checkbox: ["b"],
          inputValue: "",
          inputValue2: "",
        },
      });
    },
    formSubmit(e: WechatMiniprogram.CustomEvent) {
      console.log("form发生了submit事件，携带数据为：", this.data.formData);
      const _wxValidate = this._wxValidate;
      if (!_wxValidate.checkForm(this.data.formData)) {
        const errors = _wxValidate.validationErrors();
        console.log("errors", errors);
        const fieldsError: Record<string, string[]> = {};
        errors.forEach((item) => {
          if (fieldsError[item.param]) {
            fieldsError[item.param].push(item.msg);
          } else {
            fieldsError[item.param] = [item.msg];
          }
        });
        this.setData({ fieldsError });
      }
    },
    formReset(e: WechatMiniprogram.CustomEvent) {
      console.log("form发生了reset事件，携带数据为：", {
        switchChecked: false,
        radio: "1",
        checkbox: ["b"],
        inputValue: "",
      });
      this.setData({
        formData: {
          switchChecked: false,
          radio: "1",
          checkbox: ["b"],
          inputValue: "",
          inputValue2: "",
        },
      });
    },
    doFieldUpdateAndValidate(field: string, fieldVal: any) {
      const _wxValidate = this._wxValidate;
      const validateField = field.replace("formData.", "");
      let tmpData = {};
      if (!_wxValidate.checkOneParam(validateField, fieldVal)) {
        const errors = _wxValidate.validationErrors();
        const fieldsError: Record<string, string[]> = {
          ...this.data.fieldsError,
        };
        // 更新当前字段的错误提示信息
        errors.forEach((item) => {
          fieldsError[item.param] = [item.msg];
        });
        tmpData = { [field]: fieldVal, fieldsError };
      } else {
        const fieldsError: Record<string, string[]> = {
          ...this.data.fieldsError,
        };
        // 清除当前字段的错误提示信息
        delete fieldsError[validateField];
        tmpData = { [field]: fieldVal, fieldsError };
      }
      this.setData(tmpData);
    },
    onSwitchChange(event: WechatMiniprogram.CustomEvent) {
      const field = event.currentTarget.dataset.field as string;
      this.doFieldUpdateAndValidate(field, event.detail);
    },
    onCheckboxChange(event: WechatMiniprogram.CustomEvent) {
      const field = event.currentTarget.dataset.field as string;
      this.doFieldUpdateAndValidate(field, event.detail);
    },
    onRadioChange(event: WechatMiniprogram.CustomEvent) {
      const field = event.currentTarget.dataset.field as string;
      this.doFieldUpdateAndValidate(field, event.detail);
    },
    onInputChange(event: WechatMiniprogram.CustomEvent) {
      const field = event.currentTarget.dataset.field as string;
      this.doFieldUpdateAndValidate(field, event.detail);
    },
  },
});
